package com.mvetc.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.google.gson.Gson;
import com.mvetc.entity.PageInfo;
import com.mvetc.entity.User;
import com.mvetc.service.MovieService;
import com.mvetc.service.UserService;
import com.mvetc.service.impl.MovieServiceImpl;
import com.mvetc.service.impl.UserServiceImpl;
import com.mvetc.util.RegExUitl;
import com.mvetc.util.MD5Util;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
@MultipartConfig
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();
	private MovieService movieService = new MovieServiceImpl();


	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = request.getParameter("op");
		if ("existsOfUserName".equals(op)) {
			// 判断用户名是否存在
			doExistsOfUserName(request, response);
		} else if ("register".equals(op)) {
			// 注册
			doRegister(request, response);
		} else if ("login".equals(op)) {
			// 登录
			doLogin(request, response);
		} else if ("logout".equals(op)) {
			// 注销
			doLogOut(request, response);
		} else if ("esistOfUser".equals(op)) {
			doEsistOfUser(request, response);

		} else if ("ifLogin".equals(op)) {
			ifLogin(request, response);

		} else if ("updateInfo".equals(op)) {
			// 孙志强
			doUpdateInfo(request, response);
		} else if("getUserInfo".equals(op)) {
			getUserInfo(request,response);
		} else if (op == null || "getUserList".equals(op)) {
			doGetUserList(request,response);
		}else if ("addUserObject".equals(op)) {
			doAddUserObject(request,response);
		}else if ("updateByUserId".equals(op)) {
			doUpdateByUserId(request,response);
		}else if ("deleteByUserId".equals(op)) {
			doDeleteByUserId(request,response);
		}
	}

	private void doDeleteByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userId = request.getParameter("userId");
		userService.deleteById(userId);
		
		doGetUserList(request, response);
	}

	private void doUpdateByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String json = request.getParameter("updateUser");
		Gson gson = new Gson();
		User fromJson = gson.fromJson(json,	User.class);
		userService.modify(fromJson);
		
		doGetUserList(request, response);
	}

	private void doAddUserObject(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String json = request.getParameter("addUser");
		Gson gson = new Gson();
		User fromJson = gson.fromJson(json,	User.class);
		userService.addUser(fromJson);
		
		doGetUserList(request, response);
	}
	
	private void doGetUserList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userNameKey = request.getParameter("userNameKey");
		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");
		System.out.println(userNameKey);
		Map<String, String> map = new HashMap<>();
		map.put("userNameKey", userNameKey);
		map.put("pageNum", pageNum);
		map.put("pageSize", pageSize);
		PageInfo<User> pageInfo = userService.getBy(map);
		
		Gson gson = new Gson();
		String jsonObject = gson.toJson(pageInfo);
		
		response.setContentType("application/json");
		response.getWriter().write(jsonObject);
	}
	
	private void getUserInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
		// 孙志强
		String userName = request.getParameter("userName");
		List<Map<String, Object>> userInfoByName = movieService.getUserInfoByName(userName);
		Gson gson = new Gson();
		String userInfoJson = gson.toJson(userInfoByName);
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(userInfoJson);
		
	}

	private void doUpdateInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
		// 孙志强
		Map<String, String> set = new HashMap<>(16);
		// 获取普通参数
		String userName = request.getParameter("userName");
		String parameter = request.getParameter("userPassword");
		if (!parameter.isEmpty()) {
			String userPassword = MD5Util.getMd5(parameter);
			set.put("user_password", "'"+userPassword+"'");
		}
		
		String userContact = request.getParameter("userContact");
		String userIntro = request.getParameter("userIntro");
		// 创建part对象获取文件信息
		Part part = request.getPart("userPicture");
		String picname = part.getHeader("content-disposition");
		String patten = "(?<==\")\\S*\\.\\w*(?=\")";
		// 正则提取文件名
		List<String> picNameList = RegExUitl.regEx(patten, picname);
		String fileName = null;
		if (!picNameList.isEmpty()) {
			LocalDateTime now = LocalDateTime.now();
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSS");
			String format = dtf.format(now);
			int random = (int) (Math.random() * 10000 + 1);
			StringBuilder sBuilder = new StringBuilder();
			fileName = sBuilder.append(format).append(random).append(picNameList.get(0)).toString();
			File file = new File("D:\\fileupload\\images");
			if (!file.exists()) {
				file.mkdirs();
			}
			String filePath = file.getPath() + File.separator + fileName.toString();
			part.write(filePath);
			//如果文件名不为空，添加到集合中
			set.put("user_picture", "'"+fileName+"'");
		}
		
		
		set.put("user_name", "'"+userName+"'");
		set.put("user_contact", "'"+userContact+"'");
		set.put("user_intro", "'"+userIntro+"'");
		
		Map<String, String> where = new HashMap<>(16);
		where.put("user_name", "'"+userName+"'");
		int updateInfo = movieService.updateInfo(set, where);
		response.setContentType("application/json;charset=utf-8");
		if (updateInfo>0) {
			response.sendRedirect("front/customCenter.jsp");
		} else {
			response.getWriter().write("0");
		}
	}

	private void ifLogin(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		String Password = (String) session.getAttribute("userPassword");
		User user = userService.login(userName, Password);

		Gson gson = new Gson();
		String jsonObject = gson.toJson(user);
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(jsonObject);

	}

	private void doLogOut(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		HttpSession session = request.getSession();
		session.removeAttribute("userName");
		session.removeAttribute("userPassword");
		Gson gson = new Gson();
		String jsonObject = gson.toJson("true");
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(jsonObject);
	}

	private void doEsistOfUser(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String userName = request.getParameter("userName");
		boolean esistOfUser = userService.existsOfAccountName(userName);
		if (esistOfUser == true) {
			Gson gson = new Gson();
			String jsonObject = gson.toJson("false");
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(jsonObject);

		}
		if (esistOfUser == false) {
			Gson gson = new Gson();
			String jsonObject = gson.toJson("true");
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(jsonObject);
		}

	}

	private void doExistsOfUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 业务逻辑层
		String userName = request.getParameter("accountName");
		boolean existsOfUserName = userService.existsOfAccountName(userName);
		// 响应数据

		if (existsOfUserName == true) {
			Gson gson = new Gson();
			String jsonObject = gson.toJson("false");
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(jsonObject);

		}
		if (existsOfUserName == false) {
			Gson gson = new Gson();
			String jsonObject = gson.toJson("true");
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().write(jsonObject);
		}

	}

	private void doRegister(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// 接受普通组件

				String userName = request.getParameter("reuserName");
				
				String userPassword = request.getParameter("repassword");
				//MD5加密
				MD5Util md5util=new MD5Util();
				userPassword=md5util.getMd5(userPassword);
						
				
				// 接收文件组件
				Part part = request.getPart("facePicture");
				// 判断用户是否有上传文件
				if(part.getSize() == 0) { // 没有上传
					LocalDateTime now2 = LocalDateTime.now();
					DateTimeFormatter ofPattern2 = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
					// 将当前日期时间转成字符串
					String formatDate2 = ofPattern2.format(now2);
					int random2 = (int) (Math.random()*100+1);
					StringBuffer useid = new StringBuffer();
					useid.append(formatDate2).append(random2);
					// 业务逻辑层
					User user = new User(useid.toString(), userName, userPassword, "123456.jpg", "0");
					int n=userService.register(user);
					Gson gson = new Gson();
					String jsonObject = gson.toJson(n);
					response.setContentType("application/json;charset=utf-8");
					response.getWriter().write(jsonObject);
				}else { // 有上传
					
					// 允许的文件图片类型
					String allowImgType ="image/jpg,image/jpeg,image/png";
					// 允许的文件图片类型集合
					List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));
					
					// 判断上传的文件类型是否合法
					String contentType = part.getContentType(); // 获取上传文件的MIME类型
					
					// 判断上传的文件MIME类型是否在指定的允许类型集合
					if(allowImgTypeList.contains(contentType)==false) {
						
						// 重定向注册页面,提示文件不合法
						response.sendRedirect("front/index.jsp?fileuploaderror=fileuploaderror");
						return;
					}else {
						// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
						String header = part.getHeader("content-disposition");
						String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
						// 获取真实文件名的后缀
						String fileSuffix = realName.substring(realName.lastIndexOf("."));
						// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
						// JDK1.8 日期时间类
						LocalDateTime now = LocalDateTime.now();
						DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
						// 将当前日期时间转成字符串
						String formatDate = ofPattern.format(now);	
						// 随机数
						int random = (int) (Math.random()*1000+1);
						// 拼接
						StringBuffer fileName = new StringBuffer();
						fileName.append(formatDate).append(random);
						
						// 将文件存储在指定服务器中(本地电脑E盘)
						File file = new File("D:\\fileupload\\images");
						
						// 将文件写入指定位置
						String filePath = file.getPath() + File.separator + fileName + fileSuffix; // E:\fileupload\images\1.jpg
						part.write(filePath);
						
						// 调用业务层
						LocalDateTime now2 = LocalDateTime.now();
						DateTimeFormatter ofPattern2 = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
						// 将当前日期时间转成字符串
						String formatDate2 = ofPattern2.format(now2);
						int random2 = (int) (Math.random()*100+1);
						StringBuffer useid = new StringBuffer();
						useid.append(formatDate2).append(random2);
						User user = new User(useid.toString(), userName, userPassword, fileName + fileSuffix,"0"); // 数据库中仅需要存储文件名.扩展名
						int n=userService.register(user);
						Gson gson = new Gson();
						String jsonObject = gson.toJson(n);
						response.setContentType("application/json;charset=utf-8");
						response.getWriter().write(jsonObject);
					
				}
			
				// 重定向到前台首页
				
			}
		}

		// 重定向到前台首页

	

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username = request.getParameter("userName");
		String userpassword = request.getParameter("userPassword");
		String userPasswordMd5 = MD5Util.getMd5(userpassword);
		User user = userService.login(username, userPasswordMd5);

		// 将用户信息存储在session中

		HttpSession session = request.getSession();
		session.setAttribute("userName", username);
		session.setAttribute("userPassword", userPasswordMd5);

		// 响应
		Gson gson = new Gson();
		String jsonObject = gson.toJson(user);
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(jsonObject);

	}

}
